package com.ita.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ita.pojo.User;

public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String requestUri = req.getRequestURI();
		String contextPath = req.getContextPath();
		String url = requestUri.substring(contextPath.length());
		System.out.println(url);
		User user = (User) req.getSession().getAttribute("user");
		if (requestUri.indexOf("/login.jsp") > -1
				|| (requestUri.indexOf("login") > -1)) {
			chain.doFilter(req, resp);
		} else {
			if (user == null) {
				CharFilter.logger.info("redirect");
				resp.sendRedirect("login.jsp");
			} else {
				chain.doFilter(req, resp);
			}
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
